<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" class="mb-4" v-show="showSearch">
      <el-form-item label="活动标题">
        <el-input v-model="queryParams.title" placeholder="请输入活动标题" clearable />
      </el-form-item>
      <el-form-item label="活动类型" style="width:250px">
        <el-select v-model="queryParams.activityType" placeholder="请选择活动类型" clearable>
          <el-option label="邀请拉新送积分" :value="0" />
          <el-option label="充值送积分" :value="1" />
          <el-option label="其他" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" style="width: 150px">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="全部" :value="-1" />
          <el-option label="进行中" :value="1" />
          <el-option label="已下架" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="getList">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          >新增</el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="list" border>
      <el-table-column label="ID" prop="id"  align="center" />
      <el-table-column label="活动标题" prop="title" align="center" />
      <el-table-column label="活动类型" prop="activityType" align="center">
        <template #default="scope">
          {{ activityTypeLabel(scope.row.activityType) }}
        </template>
      </el-table-column>
      <el-table-column label="是否上架" width="120" align="center">
  <template #default="scope">
    <el-switch
      v-model="scope.row.status"
      :active-value="1"
      :inactive-value="0"
      @change="(val) => handleStatusChange(scope.row)"
    ></el-switch>
  </template>
</el-table-column>

      <el-table-column label="开始时间" prop="startTime" width="180" align="center" />
      <el-table-column label="结束时间" prop="endTime" width="180" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleEdit(scope.row)">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.size"
      @pagination="getList"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="open" :title="title" width="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="活动类型" prop="activityType">
          <el-select v-model="form.activityType" placeholder="请选择类型">
            <el-option label="邀请拉新送积分" :value="0" />
            <el-option label="充值送积分" :value="1" />
            <el-option label="其他" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="form.startTime" type="datetime" placeholder="选择开始时间" style="width:100%" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="form.endTime" type="datetime" placeholder="选择结束时间" style="width:100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getActivityPage,
  addActivity,
  updateActivity,
  deleteActivity,activeActivity 
} from "@/api/system/eventManagement"; // 接口封装
import dayjs from "dayjs";

// 状态与列表
const loading = ref(false);
const total = ref(0);
const list = ref([]);
const open = ref(false);
const title = ref("");
const formRef = ref(null);
const showSearch = ref(true);

// 分页与搜索参数
const queryParams = reactive({
  page: 1,
  size: 10,
  title: "",
  activityType: 0,
  status: -1,
});

// 表单数据
const form = reactive({
  id: null,
  title: "",
  activityType: 0,
  startTime: "",
  endTime: "",
  status: 1,
  description: "",
});

// 表单校验规则
const rules = {
  title: [{ required: true, message: "请输入活动标题", trigger: "blur" }],
  activityType: [{ required: true, message: "请选择活动类型", trigger: "change" }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  endTime: [{ required: true, message: "请选择结束时间", trigger: "change" }],
};

// 类型映射
const activityTypeLabel = (type) => {
  return ["邀请拉新送积分", "充值送积分", "其他"][type] || "未知";
};

// 页面初始化
onMounted(() => {
  getList();
});

// 获取活动列表
async function getList() {
  loading.value = true;
  try {
    const res = await getActivityPage(queryParams);
    if (res.code === 200 && res.data) {
      list.value = res.data.records || [];
      total.value = Number(res.data.total) || 0;
    }
  } finally {
    loading.value = false;
  }
}

// 重置搜索
function resetQuery() {
  queryParams.title = "";
  queryParams.activityType = 0;
  queryParams.status = -1;
  queryParams.page = 1;
  getList();
}

// 新增
function handleAdd() {
  title.value = "新增活动";
  Object.assign(form, {
    id: null,
    title: "",
    activityType: 0,
    startTime: "",
    endTime: "",
    status: 1,
    description: "",
  });
  open.value = true;
}

// 编辑
function handleEdit(row) {
  title.value = "编辑活动";
  Object.assign(form, JSON.parse(JSON.stringify(row)));
  open.value = true;
}

// 提交表单
async function submitForm() {
  try {
    await formRef.value.validate();

    // 格式化时间
    const submitData = {
      ...form,
      startTime: dayjs(form.startTime).format("YYYY-MM-DD HH:mm:ss"),
      endTime: dayjs(form.endTime).format("YYYY-MM-DD HH:mm:ss"),
    };

    let res;
    if (form.id) {
      res = await updateActivity(submitData);
    } else {
      res = await addActivity(submitData);
    }

    if (res.code === 0 || res.code === 200) {
      ElMessage.success("操作成功");
      open.value = false;
      getList();
    } else {
      ElMessage.error(res.msg || "操作失败");
    }
  } catch (err) {
    console.log("表单验证失败或操作异常", err);
  }
}

// 删除
function handleDelete(row) {
  ElMessageBox.confirm("确认删除该活动吗？", "提示", { type: "warning" })
    .then(async () => {
      const res = await deleteActivity(row.id);
      if (res.code === 0) {
        ElMessage.success("删除成功");
        getList();
      } else {
        ElMessage.error(res.msg || "删除失败");
      }
    })
    .catch(() => {});
}

async function handleStatusChange(row) {
  const text = row.status === 1 ? "上架" : "下架";

  try {
    await ElMessageBox.confirm(`确认要${text}该活动 "${row.title}" 吗？`);

    const res = await activeActivity(row.id, row.status);
    if (res.code === 0 || res.code === 200) {
      ElMessage.success(`${text}成功`);
    } else {
      throw new Error(res.msg || "接口错误");
    }
  } catch (err) {
    // 回滚状态
    row.status = row.status === 1 ? 0 : 1;
  }
}
</script>
